<template>
    <div>
        <!-- 头部 -->
        <van-nav-bar
            title="频道管理"
            left-arrow
            @click-left="$router.push('/index')"
            />
        <!-- 列表 -->
        <div class="content">
            <h1>点击删除频道</h1>
            <!-- column-num自定义列数 -->
            <van-grid :column-num="4" :gutter="10">
            <van-grid-item @click="delCategoryFn(index)" v-for="(value,index) in categoryList" 
            :key="value.id" :text="value.name" />
            </van-grid>
        </div>
        <div class="content">
            <h1>点击添加频道</h1>
            <!-- column-num自定义列数 -->
            <van-grid :column-num="4" :gutter="10">
            <van-grid-item @click="addCategoryFn(index)" v-for="(value,index) in delCategory" :key="value.id" :text="value.name" />
            </van-grid>
        </div>
    </div>
</template>

<script>
import  { category } from "@/api/common.js"
export default {
    data(){
        return {
            categoryList: [],
            delCategory: []
        }
    },
    created(){
        // 当缓存中存在栏目列表的时候，栏目列表的数据就可以直接从缓存中获取。
        // 否则调用接口从后端获取
        if(localStorage.getItem("categoryList")||localStorage.getItem("delCategory")){
            this.categoryList = JSON.parse(localStorage.getItem("categoryList"))
            this.delCategory = JSON.parse(localStorage.getItem("delCategory"))
            return
        }
        category().then(res=>{
            // console.log(32,res);
            this.categoryList = res.data.data;
            // 删除“关注”和“头条”数据
            let num = localStorage.getItem("hm-token-71")?2:1;
            // this.categoryList.slice(0,num)
            let result = this.categoryList.splice(0,num);
            // console.log(52,result);缓存“关注”和“头条”
            localStorage.setItem("defaultCategory", JSON.stringify(result));
        })
    },
    methods: {
        // 删除栏目
        delCategoryFn(index){
            let res =  this.categoryList.splice(index,1);
            // console.log(47,res);
            this.delCategory.push(...res);
            // 缓存数据
            localStorage.setItem("categoryList",JSON.stringify(this.categoryList))
            localStorage.setItem("delCategory",JSON.stringify(this.delCategory))
        },
        // 添加栏目
        addCategoryFn(index){
            let res = this.delCategory.splice(index,1);
            this.categoryList.push(...res);
            // 缓存数据
            localStorage.setItem("categoryList",JSON.stringify(this.categoryList))
            localStorage.setItem("delCategory",JSON.stringify(this.delCategory))
        }
    }
}
</script>
<style lang="less" scoped>
.content{
    padding: 20px 10px;
    h1{
        margin-bottom: 20px;
    }
    /deep/.van-grid-item__content{
        border: 1px solid #ddd;
    }
}
</style>